package com.example.aicloud.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 创建线程池
 * @author Mr.Tang
 * @date 2024-07-28
 */
@Configuration
public class ThreadPoolConfig {
    @Bean
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置线程池 核心线程数 (设置为 当前cup的核数 + 1)
        executor.setCorePoolSize(Runtime.getRuntime().availableProcessors() + 1);
        // 设置线程池 最大线程数
        executor.setMaxPoolSize(Runtime.getRuntime().availableProcessors() * 2 + 1);
        // 设置线程池 任务队列 容量
        executor.setQueueCapacity(100000);
        // 自定义 拒绝策略
        executor.setRejectedExecutionHandler(new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                // TODO:1. 保存拒绝的任务
                // TODO:2. 通知相关负责人进行手动处理
            }
        });
        // 执行初始化
        executor.initialize();
        return executor;
    }

}
